<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌" prop="brand">
        <el-input v-model.trim="queryParams.brand" placeholder="请输入品牌" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="渠道" prop="channel">
        <el-input v-model.trim="queryParams.channel" placeholder="请输入渠道" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-input v-model.trim="queryParams.shopName" placeholder="请输入店铺名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="!isOpen ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" size="mini"
          @click="shouqi">展开/收起</el-button>
      </el-form-item>
      <div v-if="isOpen">
        <el-form-item label="店铺id" prop="shopId">
          <el-input v-model.trim="queryParams.shopId" placeholder="请输入店铺id" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="抖音号名称" prop="douyinName">
          <el-input v-model.trim="queryParams.douyinName" placeholder="请输入抖音号名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="抖音号ID" prop="douyinId">
          <el-input v-model.trim="queryParams.douyinId" placeholder="请输入抖音号ID" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="日期" prop="dataDate">
          <el-date-picker clearable v-model="queryParams.dataDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="roi2数据阶段" prop="roi2DataStage">
          <el-input v-model.trim="queryParams.roi2DataStage" placeholder="请输入roi2数据阶段" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="整体消耗" prop="totalConsumption">
          <el-input v-model.trim="queryParams.totalConsumption" placeholder="请输入整体消耗" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="整体支付ROI" prop="totalPaymentRoi">
          <el-input v-model.trim="queryParams.totalPaymentRoi" placeholder="请输入整体支付ROI" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="整体成交金额" prop="totalTransactionAmount">
          <el-input v-model.trim="queryParams.totalTransactionAmount" placeholder="请输入整体成交金额" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="整体成交订单数" prop="totalOrderCount">
          <el-input v-model.trim="queryParams.totalOrderCount" placeholder="请输入整体成交订单数" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="整体成交订单成本" prop="totalOrderCost">
          <el-input v-model.trim="queryParams.totalOrderCost" placeholder="请输入整体成交订单成本" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="全域推广消耗占比" prop="totalConsumptionRatio">
          <el-input v-model.trim="queryParams.totalConsumptionRatio" placeholder="请输入全域推广消耗占比" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="逻辑删除" prop="isDelete">
          <el-input v-model.trim="queryParams.isDelete" placeholder="请输入逻辑删除" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
      </div>
      <!-- <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['sale:BiDyMarketingCost:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['sale:BiDyMarketingCost:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['sale:BiDyMarketingCost:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['sale:BiDyMarketingCost:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-upload
          ref="daoru"
          :action="Upload.url"
          :headers="Upload.headers"
          :limit="limit"
          :on-exceed="handleExceed"
          :on-success="handlePictureSuccessPic"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePictureCardPreview"
          :file-list="fileLi"
          :on-change="changeFile1"
        >
          <el-button size="small">导入文件</el-button>
          
        </el-upload> -->
        <el-button size="mini" plain icon="el-icon-upload" @click="daoru">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 添加或修改产品二级信息对话框 :on-change="handleChange"-->
    <el-dialog title="导入" :visible.sync="dialogVisible" width="500px" append-to-body v-if="dialogVisible">
      <!-- 文件上传-->
      <el-form :rules="rules" :model="dataForm" ref="dataForm" label-width="150px" @submit.native.prevent>
        <el-form-item label="店铺：" prop="name">
          <!-- <el-input
            type="text"
            v-model.trim="dataForm.name"
            clearable
          ></el-input> -->
          <el-cascader class="region" v-model="dataForm.name" placeholder="选择店铺分组" :options="cascadeList"
            :props="{ checkStrictly: true }" style="width: 300px; height: 30px">
          </el-cascader>
        </el-form-item>
        <el-form-item label="文件：" prop="file">
          <el-upload class="upload-import" ref="uploadImport" :http-request="httpRequest" action=""
            :on-remove="handleRemove" :file-list="fileList" :limit="1" :on-change="handleChange" :auto-upload="false"
            :before-upload="beforeAvatarUpload">
            <!--
            accept="application/zip,.zip" 设置接收的文件类型-->
            <el-button v-show="!hasFile" slot="trigger" size="small" type="primary">选取文件</el-button>
            <!-- <div slot="tip" class="el-upload__tip">
          只能上传zip文件，且不超过10M
        </div> -->
          </el-upload>
          <!-- 关闭自动上传-->
        </el-form-item>
        <el-form-item label="日期" prop="dataDate">
          <el-date-picker clearable v-model="dataForm.dataDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitUpload">提交</el-button>
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
          <el-button @click="dialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table v-loading="loading" :data="BiDyMarketingCostList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="渠道" align="center" prop="channel" />
      <el-table-column label="店铺名称" align="center" prop="shopName" />
      <el-table-column label="店铺id" align="center" prop="shopId" />
      <el-table-column label="抖音号名称" align="center" prop="douyinName" />
      <el-table-column label="抖音号ID" align="center" prop="douyinId" />
      <el-table-column label="日期" align="center" prop="dataDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dataDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="roi2数据阶段" align="center" prop="roi2DataStage" />
      <el-table-column label="整体消耗" align="center" prop="totalConsumption" />
      <el-table-column label="整体支付ROI" align="center" prop="totalPaymentRoi" />
      <el-table-column label="整体成交金额" align="center" prop="totalTransactionAmount" />
      <el-table-column label="整体成交订单数" align="center" prop="totalOrderCount" />
      <el-table-column label="整体成交订单成本" align="center" prop="totalOrderCost" />
      <el-table-column label="全域推广消耗占比" align="center" prop="totalConsumptionRatio" />
      <el-table-column label="逻辑删除" align="center" prop="isDelete" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['sale:BiDyMarketingCost:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['sale:BiDyMarketingCost:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改抖音营销花费对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌" prop="brand">
          <el-input v-model.trim="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="渠道" prop="channel">
          <el-input v-model.trim="form.channel" placeholder="请输入渠道" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model.trim="form.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="店铺id" prop="shopId">
          <el-input v-model.trim="form.shopId" placeholder="请输入店铺id" />
        </el-form-item>
        <el-form-item label="抖音号名称" prop="douyinName">
          <el-input v-model.trim="form.douyinName" placeholder="请输入抖音号名称" />
        </el-form-item>
        <el-form-item label="抖音号ID" prop="douyinId">
          <el-input v-model.trim="form.douyinId" placeholder="请输入抖音号ID" />
        </el-form-item>
        <el-form-item label="日期" prop="dataDate">
          <el-date-picker clearable v-model="form.dataDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="roi2数据阶段" prop="roi2DataStage">
          <el-input v-model.trim="form.roi2DataStage" placeholder="请输入roi2数据阶段" />
        </el-form-item>
        <el-form-item label="整体消耗" prop="totalConsumption">
          <el-input v-model.trim="form.totalConsumption" placeholder="请输入整体消耗" />
        </el-form-item>
        <el-form-item label="整体支付ROI" prop="totalPaymentRoi">
          <el-input v-model.trim="form.totalPaymentRoi" placeholder="请输入整体支付ROI" />
        </el-form-item>
        <el-form-item label="整体成交金额" prop="totalTransactionAmount">
          <el-input v-model.trim="form.totalTransactionAmount" placeholder="请输入整体成交金额" />
        </el-form-item>
        <el-form-item label="整体成交订单数" prop="totalOrderCount">
          <el-input v-model.trim="form.totalOrderCount" placeholder="请输入整体成交订单数" />
        </el-form-item>
        <el-form-item label="整体成交订单成本" prop="totalOrderCost">
          <el-input v-model.trim="form.totalOrderCost" placeholder="请输入整体成交订单成本" />
        </el-form-item>
        <el-form-item label="全域推广消耗占比" prop="totalConsumptionRatio">
          <el-input v-model.trim="form.totalConsumptionRatio" placeholder="请输入全域推广消耗占比" />
        </el-form-item>
        <el-form-item label="逻辑删除" prop="isDelete">
          <el-input v-model.trim="form.isDelete" placeholder="请输入逻辑删除" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBiDyMarketingCost,
  getBiDyMarketingCost,
  delBiDyMarketingCost,
  addBiDyMarketingCost,
  updateBiDyMarketingCost,
} from "@/api/sale/BiDyMarketingCost";
//--------导入token
import { getToken } from "@/utils/auth";
import axios from "axios";
import { listAll, importBiKeyword } from "@/api/chart/brandChannelShop";
export default {
  name: "BiDyMarketingCost",
  data() {
    return {
      hasFile: false,
      fileList: [],
      dialogVisible: false,
      pjtUrl: process.env.VUE_APP_BASE_API,
      isOpen: false,
      cascadeList: [],
      dataForm: {
        name: ["VFU", "抖音", "VFU官方旗舰店"],
        file: null,
        dataDate: null,
      },

      fileLi: [],
      file: "",

      // 图片数量限制
      limit: 2,
      Upload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址:
        url:
          process.env.VUE_APP_BASE_API +
          "/marketing/BiDyMarketingDwd/importData",
      },
      isOpen: false,
      inputValue: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 抖音营销花费表格数据
      BiDyMarketingCostList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brand: null,
        channel: null,
        shopName: null,
        shopId: null,
        douyinName: null,
        douyinId: null,
        dataDate: null,
        roi2DataStage: null,
        totalConsumption: null,
        totalPaymentRoi: null,
        totalTransactionAmount: null,
        totalOrderCount: null,
        totalOrderCost: null,
        totalConsumptionRatio: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    this.getdataSourceList();
  },
  methods: {
    //搜索栏展示与收起
    shouqi() {
      // console.log(1);
      this.isOpen = !this.isOpen;
    },
    /** 查询抖音营销花费列表 */
    getList() {
      this.loading = true;
      listBiDyMarketingCost(this.queryParams).then((response) => {
        this.BiDyMarketingCostList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        brand: null,
        channel: null,
        shopName: null,
        shopId: null,
        douyinName: null,
        douyinId: null,
        dataDate: null,
        roi2DataStage: null,
        totalConsumption: null,
        totalPaymentRoi: null,
        totalTransactionAmount: null,
        totalOrderCount: null,
        totalOrderCost: null,
        totalConsumptionRatio: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加抖音营销花费";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBiDyMarketingCost(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改抖音营销花费";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiDyMarketingCost(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBiDyMarketingCost(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除抖音营销花费编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBiDyMarketingCost(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "sale/BiDyMarketingCost/export",
        {
          ...this.queryParams,
        },
        `BiDyMarketingCost_${new Date().getTime()}.xlsx`
      );
    },
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传导入文件大小不能超过 100MB!");
      }

      return isLt2M;
    },
    handleRemove(file, fileList) {
      if (!fileList.length) {
        this.hasFile = false;
      }
      this.dataForm.file = null;
    },
    handleChange(file, fileList) {
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.dataForm.file = file;
    },
    //确定按钮
    //调用组件upload的submit方法，从而触发httpRequest方法，实现手动上传
    submitUpload() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$refs.uploadImport.submit();
        }
      });
    },
    httpRequest(param) {
      if (this.dataForm.name.length < 3) {
        this.$modal.msgWarning("请选择到店铺");
        return;
      }
      let fd = new FormData();
      fd.append("file", param.file); // 传文件
      //   fd.append("salesGrade", this.dataForm.name);
      //dataPar.file.raw
      console.log(JSON.stringify(fd));
      this.openLoading();
      axios
        .post(
          process.env.VUE_APP_BASE_API +
          "/sale/BiDyMarketingCost/importData?salesGrade=" +
          this.dataForm.name + '&dataDate=' + this.dataForm.dataDate,
          fd,
          {
            headers: {
              header: { responseType: "blob" },

              Authorization: "Bearer " + getToken(),
              "Content-Type": "multipart/form-data",
            }, //定义内容格式,很重要
            // timeout: 20000,
          }
        )
        .then((response) => {
          console.log(response);
          if (response.data.code == 200) {
            this.dialogVisible = false;
            this.$modal.closeLoading();
            this.$modal.msgSuccess("导入成功");
            this.hasFile = false;
            this.getList();
          }
        });
    },
    //部门文件导入修改打开
    daoru() {
      this.dialogVisible = true;
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在导入，请稍候！");
    },
    /** 查询品牌渠道店铺关系列表 */
    getdataSourceList() {
      listAll().then((response) => {
        // let list = [];
        // response.forEach((item) => {
        //   if (item.isTalentLive == "是") {
        //     list.push(item);
        //   }
        // });
        let result = this.transformData(response);
        this.cascadeList = result;
        this.dataForm.name = [
          result[0].label,
          result[0].children[0].label,
          result[0].children[0].children[0].label,
        ];
      });
    },
    //店铺渠道品牌转换

    transformData(data) {
      let result = [];

      data.forEach((item) => {
        let brand = item.brand;
        let channel = item.channel;
        let shopName = item.channelShopName;

        // 如果brand在结果数组中不存在，则创建一个新的数组
        let brandIndex = result.findIndex(
          (brandObj) => brandObj.label === brand
        );
        if (brandIndex === -1) {
          result.push({
            label: brand,
            value: brand,
            children: [],
            disabled: true,
          });
          brandIndex = result.length - 1;
        }

        // 如果channel在当前brand的children数组中不存在，则创建一个新的数组
        let channelIndex = result[brandIndex].children.findIndex(
          (channelObj) => channelObj.label === channel
        );
        if (channelIndex === -1) {
          result[brandIndex].children.push({
            label: channel,
            value: channel,
            children: [],
            disabled: true,
          });
          channelIndex = result[brandIndex].children.length - 1;
        }

        // 如果shopName在当前channel的children数组中不存在，则创建一个新的数组
        let shopIndex = result[brandIndex].children[
          channelIndex
        ].children.findIndex((shopObj) => shopObj.label === shopName);
        if (shopIndex === -1) {
          result[brandIndex].children[channelIndex].children.push({
            label: shopName,
            value: shopName,
            // children: []
          });
        }
      });

      return result;
    },
  },
};
</script>
